import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/Topic.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/database/db_praise.dart';
import 'package:flutter_chip/utils/comm_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/view/home/mcu_web.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:flutter_chip/widget/view_image.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';
import 'package:fsuper/fsuper.dart';

class ForumListPage extends StatefulWidget {
  final title;

  const ForumListPage({Key key, this.title}) : super(key: key);

  @override
  _ForumListPageState createState() => _ForumListPageState();
}

class _ForumListPageState extends StateWithLifecycle<ForumListPage>
    with AutomaticKeepAliveClientMixin {
  EasyRefreshController controller = EasyRefreshController();

  int childCount = 0;

  //数据集合
  var _item = [];
  int pageNum = 0;

  //数据库
  PraiseDao _praiseDao = PraiseDao();

  //所有点赞列表
  Set<String> _praiseSets;

  @override
  void onResume() {
    super.onResume();
    _loadData(true);
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh.custom(
      enableControlFinishRefresh: true,
      enableControlFinishLoad: true,
      header: CommWidget.commHeader(),
      footer: CommWidget.commFooter(),
      emptyWidget: childCount == 0 ? CommWidget.nullWidget() : null,
      controller: controller,
      slivers: <Widget>[
        SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
          return _itemView(context, index);
        }, childCount: childCount))
      ],
      onRefresh: () => _loadData(true),
      onLoad: () => _loadData(false),
    );
  }

  Widget _itemView(BuildContext context, int index) {
    Topic topic = _item[index];
    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _itemUser(topic),
          GestureDetector(
              child: _itemTopic(topic),
              onTap: () {
                if (topic.content.startsWith("![")) {
                  Navigator.of(context).push(
                    MaterialPageRoute(builder: (_) {
                      return WebInfoPage(
                          topic.title, topic.content.substring(2),
                          type: "web");
                    }),
                  );
                  return;
                }
                String url =
                    "${Routers.PAGE_FORUMINFO}?topicId=${topic.topicId}";
                Routers.router.navigateTo(context, url,
                    transition: TransitionType.inFromRight);
              }),
          SizedBox(height: 16),
          Container(
            child: _itemButtom(topic),
            padding: EdgeInsets.only(left: 10, right: 10),
          ),
          SizedBox(height: 10),
          Container(color: Color(0xfff2f2f2), height: 8)
        ]);
  }

  ///用户信息
  Widget _itemUser(Topic topic) {
    return FSuper(
      margin: EdgeInsets.only(top: 10),
      width: double.infinity,
      child2: ClipRRect(
        borderRadius: BorderRadius.circular(15),
        child: CachedNetworkImage(
          width: 30,
          height: 30,
          imageUrl: Api.getUrl(topic.imgUrl),
          fit: BoxFit.cover,
          errorWidget: (context, url, error) =>
              Image.asset(Comm.IMG_DEFAULT, fit: BoxFit.cover),
        ),
      ),
      child2Alignment: Alignment.centerLeft,
      child2Margin: EdgeInsets.only(left: 10),
      spans: [
        TextSpan(
          text: null == topic.userName ? "" : topic.userName,
          style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500),
        ),
        TextSpan(
          text: '\n${CommUtil.getTimeDiff(topic.replyAt)}',
          style: TextStyle(fontSize: 11, color: Colors.grey),
        ),
      ],
      textAlignment: Alignment.centerLeft,
      textAlign: TextAlign.start,
      padding: EdgeInsets.only(left: 46),
      onChild2Click: () {
        Routers.router.navigateTo(
            context, "${Routers.PAGE_USERINFO}?userId=${topic.userId}",
            transition: TransitionType.inFromRight);
      },
    );
  }

  ///中间话题内容
  Widget _itemTopic(Topic topic) {
    bool showTitle = null == topic.title || topic.title.isEmpty;
    bool showPic = null != topic.imageUrls && topic.imageUrls.isNotEmpty;
    Widget picWidget;
    if (showPic) {
      List<String> images = topic.imageUrls.split(",");
      List<Widget> childs = images.map((item) {
        BorderRadius borderRadius;
        if (images.length == 1) {
          borderRadius = BorderRadius.circular(6);
        } else if (item == images.first) {
          borderRadius = BorderRadius.only(
              topLeft: Radius.circular(6),
              topRight: Radius.circular(0),
              bottomLeft: Radius.circular(6),
              bottomRight: Radius.circular(0));
        } else if (item == images.last) {
          borderRadius = BorderRadius.only(
              topLeft: Radius.circular(0),
              topRight: Radius.circular(6),
              bottomLeft: Radius.circular(0),
              bottomRight: Radius.circular(6));
        } else {
          borderRadius = BorderRadius.circular(0);
        }
        double picWidth =
            MediaQuery.of(context).size.width / images.length - 12;
        if (images.length == 1) {
          picWidth = MediaQuery.of(context).size.width / images.length - 20;
        }
        return GestureDetector(
            child: Container(
              width: picWidth,
              height: picWidth * 3 / 4,
              child: ClipRRect(
                borderRadius: borderRadius,
                child: CachedNetworkImage(
                  imageUrl: Api.getUrl(item),
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) => CommWidget.imgError(),
                ),
              ),
            ),
            onTap: () {
              int current = images.indexOf(item);
              Navigator.of(context).push(
                RouteSlide(
                  ImagePage(images, current: current),
                ),
              );
            });
      }).toList();
      picWidget = Container(
        padding: EdgeInsets.only(left: 10, right: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: childs,
        ),
      );
    }
    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          SizedBox(height: 10),
          Offstage(
              offstage: showTitle,
              child: Container(
                padding: EdgeInsets.only(left: 10, right: 10),
                child: Text(!showTitle ? topic.title : '没有内容',
                    style: TextStyle(fontWeight: FontWeight.bold)),
                width: MediaQuery.of(context).size.width,
              )),
          Offstage(offstage: showTitle, child: SizedBox(height: 6)),
          Offstage(
            offstage: topic.content.startsWith("!["),
            child: Container(
              padding: EdgeInsets.only(left: 10, right: 10),
              width: MediaQuery.of(context).size.width,
              child: Text(topic.content),
            ),
          ),
          Offstage(offstage: !showPic, child: SizedBox(height: 6)),
          Offstage(offstage: !showPic, child: picWidget)
        ]);
  }

  ///底部按钮
  Widget _itemButtom(Topic topic) {
    bool isPraise = null != _praiseSets && _praiseSets.contains(topic.topicId);
    Color colorPraise = isPraise ? Colors.redAccent : Color(0xff999999);
    TextStyle stylePraise = TextStyle(color: colorPraise);

    return Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          GestureDetector(
              child: Row(children: <Widget>[
                Icon(Icons.share, size: 18, color: Color(0xff999999)),
                SizedBox(width: 4),
                Text('分享', style: TextStyle(color: Color(0xff999999)))
              ]),
              onTap: () {}),
          SizedBox(width: 16),
          GestureDetector(
              child: Row(children: <Widget>[
                Icon(Icons.speaker_notes, size: 18, color: Color(0xff999999)),
                SizedBox(width: 4),
                Text('${topic.repayCount}',
                    style: TextStyle(color: Color(0xff999999)))
              ]),
              onTap: () {
                if (topic.content.startsWith("![")) {
                  Navigator.of(context).push(
                    MaterialPageRoute(builder: (_) {
                      return WebInfoPage(
                          topic.title, topic.content.substring(2),
                          type: "web");
                    }),
                  );
                  return;
                }
                String url =
                    "${Routers.PAGE_FORUMINFO}?topicId=${topic.topicId}";
                Routers.router.navigateTo(context, url,
                    transition: TransitionType.inFromRight);
              }),
          SizedBox(width: 16),
          GestureDetector(
              child: Row(children: <Widget>[
                Icon(Icons.thumb_up, size: 18, color: colorPraise),
                SizedBox(width: 4),
                Text('${topic.praiseCount}', style: stylePraise)
              ]),
              onTap: () async {
                if (!isPraise) {
                  _praiseDao.insert(topic.topicId);
                  _praiseSets = await _praiseDao.queryAll();
                  _update(topic.topicId, 1);
                  setState(() {
                    topic.isPraise = true;
                    topic.praiseCount++;
                  });
                } else {
                  _praiseDao.delPraise(topic.topicId);
                  _praiseSets = await _praiseDao.queryAll();
                  _update(topic.topicId, -1);
                  setState(() {
                    topic.isPraise = false;
                    if (topic.praiseCount > 0) {
                      topic.praiseCount--;
                    }
                  });
                }
              }),
        ]);
  }

  ///加载数据
  Future<void> _loadData(bool isRefresh) async {
    if (isRefresh) {
      pageNum = 0;
    }
    _praiseSets = await _praiseDao.queryAll();
    Map<String, String> params = Map();
    params["pageNum"] = "$pageNum";
    params["typeDesc"] = widget.title;
    await Http.get(Api.URL_TOPIC_LIST, params: params, successCallBack: (data) {
      print(json.decode(data));
      List list = json.decode(data).map((m) => Topic.fromJson(m)).toList();
      setState(() {
        if (isRefresh) {
          _item.clear();
          controller.finishRefresh();
        } else {
          controller.finishLoad(noMore: null != list && list.length < 10);
        }
        _item.addAll(list);
        childCount = _item.length;
        pageNum++;
      });
    }, errorCallBack: (msg) {
      Toast.show(msg);
      if (isRefresh) {
        controller.finishRefresh();
      } else {
        controller.finishLoad();
      }
    });
  }

  void _update(String topicId, int praise) {
    Map<String, String> params = Map();
    params["topicId"] = topicId;
    params["praiseCount"] = "$praise";
    Http.post(Api.URL_TOPIC_UPDATE, params: params);
  }

  @override
  bool get wantKeepAlive => true;
}
